package com.jxtti.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jxtti.entity.Attach;



public class FileOperate {
	
	
	
	
	//保存附件.
		public static  List<Attach>  savefile(HttpServletResponse response, HttpServletRequest request) throws IOException
		{
			List<Attach>  lstAttach = new ArrayList<Attach>();
			
			String upfile = request.getParameter("fileToUpload");
			
			MultipartHttpServletRequest multipartRequest = null ;
			try{
				 multipartRequest = (MultipartHttpServletRequest)request;
			}catch(Exception e){
				return lstAttach;
			}
			List<MultipartFile> files = multipartRequest.getFiles("fileToUpload");
			for(MultipartFile file:files){
				if (file == null || file.isEmpty()) {      
					continue;
				  }
				Attach instance = new Attach();
				
				String basePath = request.getContextPath();  
				basePath = request.getScheme()+"://"+ServerUtil.getLocalIP() +":"+request.getServerPort()+basePath+"/".concat("upload"); //访问路径。
				
				String savePath = request.getSession().getServletContext().getRealPath("").concat("\\").concat("upload"); //保存路径.
				
				String filename = file.getOriginalFilename();
				
				String fm = filename.substring(filename.lastIndexOf("."), filename.length());  //取文件格式。，
				
				String fullFileName = generateRandomFilename().concat(fm);  //随机产生的文章名.
				String fullpath = basePath.concat("/").concat(fullFileName);
				
				instance.setAttach_name(filename);
				instance.setAttach_path(fullpath);
				SaveFileFromInputStream(file.getInputStream(), savePath, fullFileName);
				
				lstAttach.add(instance);
			}
			return lstAttach;
		}
		
		public static  boolean SaveFileFromInputStream(InputStream stream, String path,
				String filename) {
			try {
				File file = new File(path + "/" + filename);
				File parent = file.getParentFile();

				if (parent != null && !parent.exists()) {
					parent.mkdirs();
				}
				FileOutputStream fs = new FileOutputStream(path + "/" + filename);
				byte[] buffer = new byte[1024 * 1024];
				int bytesum = 0;
				int byteread = 0;
				while ((byteread = stream.read(buffer)) != -1) {
					bytesum += byteread;
					fs.write(buffer, 0, byteread);
					fs.flush();
				}
				fs.close();
				stream.close();
			} catch (IOException e) {
				e.getMessage();
				return false;
			} catch (Exception e) {
				e.getMessage();
				return false;
			}
			return true;
		}
		
		
		
		
		/**
		 * 上传附件
		 * @param entity 附件实体
		 * @param response
		 * @param request
		 * @param uploadflod   文件夹名.
		 * @return
		 * @throws IOException
		 */
		public static  List<Attach>  savefile(HttpServletResponse response, HttpServletRequest request, String uploadflod) throws IOException
		{
			List<Attach>  lstAttach = new ArrayList();
			
			String upfile = request.getParameter("fileToUpload");
			
			MultipartHttpServletRequest multipartRequest = null ;
			try{
				 multipartRequest = (MultipartHttpServletRequest)request;
			}catch(Exception e){
				
				return lstAttach;
			}
			List<MultipartFile> files = multipartRequest.getFiles("fileToUpload");
			for(MultipartFile file:files){
				if (file == null || file.isEmpty()) {      
					continue;
				  }
				Attach instance = new Attach();
				
				String basePath = request.getContextPath();  
				basePath = /*request.getScheme()+"://"+ServerUtil.getLocalIP() +":"+request.getServerPort()*/ basePath+"/".concat(uploadflod); //访问路径。
				
				String savePath = request.getSession().getServletContext().getRealPath("").concat("\\").concat(uploadflod); //保存路径.
				
				String filename = file.getOriginalFilename();
				
				String fm = filename.substring(filename.lastIndexOf("."), filename.length());  //取文件格式。，
				
				String fullFileName = generateRandomFilename().concat(fm);  //随机产生的文章名.
				String fullpath = basePath.concat("/").concat(fullFileName);
				instance.setAttach_size(file.getSize());
				instance.setAttach_name(filename);
				instance.setAttach_path(fullpath);
		
				SaveFileFromInputStream(file.getInputStream(), savePath, fullFileName);
				
				lstAttach.add(instance);
			}
			return lstAttach;
		}
		
		

		/**
		 * 上传附件
		 * @param entity 附件实体
		 * @param response
		 * @param request
		 * @param uploadflod   文件夹名.
		 * @return
		 * @throws IOException
		 */
		public static  List<Attach>  savefile(HttpServletResponse response, HttpServletRequest request, String uploadflod, String fileName) throws IOException
		{
			List<Attach>  lstAttach = new ArrayList();
			
			String upfile = request.getParameter("fileToUpload");
			
			MultipartHttpServletRequest multipartRequest = null ;
			try{
				 multipartRequest = (MultipartHttpServletRequest)request;
			}catch(Exception e){
				
				return lstAttach;
			}
			List<MultipartFile> files = multipartRequest.getFiles(fileName);
			for(MultipartFile file:files){
				if (file == null || file.isEmpty()) {      
					continue;
				  }
				Attach instance = new Attach();
				
				String basePath = request.getContextPath();  
				basePath = /*request.getScheme()+"://"+ServerUtil.getLocalIP() +":"+request.getServerPort()*/ basePath+"/".concat(uploadflod); //访问路径。
				
				String savePath = request.getSession().getServletContext().getRealPath("").concat("\\").concat(uploadflod); //保存路径.
				
				String filename = file.getOriginalFilename();
				
				String fm = filename.substring(filename.lastIndexOf("."), filename.length());  //取文件格式。，
				
				String fullFileName = generateRandomFilename().concat(fm);  //随机产生的文章名.
				String fullpath = basePath.concat("/").concat(fullFileName);
				instance.setAttach_size(file.getSize());
				instance.setAttach_name(filename);
				instance.setAttach_path(fullpath);
		
				SaveFileFromInputStream(file.getInputStream(), savePath, fullFileName);
				
				lstAttach.add(instance);
			}
			return lstAttach;
		}
		
		
		
		/*  
	     * 生成随机文件名  
	     */    
	    public static  String generateRandomFilename(){    
	        String RandomFilename = "";    
	        Random rand = new Random();//生成随机数    
	        int random = rand.nextInt();    
	            
	        Calendar calCurrent = Calendar.getInstance();    
	        int intDay = calCurrent.get(Calendar.DATE);    
	        int intMonth = calCurrent.get(Calendar.MONTH) + 1;    
	        int intYear = calCurrent.get(Calendar.YEAR);    
	        String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" + String.valueOf(intDay) + "_";       
	            
	        RandomFilename = now + String.valueOf(random > 0 ? random : ( -1) * random);    
	            
	        return RandomFilename;    
	    }  
	    
	
	    
	    /**
	     * 下载实现.
	     * @param url
	     * @param dir
	     * @return
	     */
	    public static String downloadFromUrl(String url,String dir) {  
	    	  
	        try {  
	            URL httpurl = new URL(url);  
	            String fileName = getFileNameFromUrl(url);  
	            System.out.println(fileName);  
	            File f = new File(dir + fileName);  
	            FileUtils.copyURLToFile(httpurl, f);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	            return "Fault!";  
	        }   
	        return "Successful!";  
	    }  
	      
	    public static String getFileNameFromUrl(String url){  
	        String name = new Long(System.currentTimeMillis()).toString() + ".X";  
	        int index = url.lastIndexOf("/");  
	        if(index > 0){  
	            name = url.substring(index + 1);  
	            if(name.trim().length()>0){  
	                return name;  
	            }  
	        }  
	        return name;  
	    }  
	    
	    
	    /**
	     * 返回文件名.
	     * @param url
	     * @return
	     * @throws IOException
	     */
	    public static  String  downLoad_OA_Doc(String url) throws IOException
	    {
	    	String fileName =getFileNameFromUrl(url);
	    	String localPath = CommConstant.DOC_SAVE_PATH + fileName;
	    	
	    	 URL httpurl = new URL(url);  
	        
	         File f = new File(localPath);  
	         FileUtils.copyURLToFile(httpurl, f);  
	         return fileName;
	    }
	    
	    
	    /**
	     * 返回文件名.
	     * @param url
	     * @return
	     * @throws IOException
	     */
	    public static  String  downLoad_OA_Doc_Attach(String url, String fileName) throws IOException
	    {
	    	
	    	String localPath = CommConstant.DOC_SAVE_PATH + fileName;
	    	
	    	 URL httpurl = new URL(url);  
	        
	         File f = new File(localPath);  
	         FileUtils.copyURLToFile(httpurl, f);  
	         return fileName;
	    }
	    
	    
	    
	    public static void main(String args[])
	    {
	    	downloadFromUrl("http://10.162.121.50/TsysFilesInfo/tsysfilesinfo!downloadByPath.action?pathNoNeedOrgId=true&path=20111229101704767016000000000000/tdocDocumentsrelease/8a22f9b25418549e0154185623300002/zw.pdf", "f://a.pdf");
	    }
	    
	    
	    
	    public static  void downloadFile(String remoteFilePath, String localFilePath)
		 {
		        URL urlfile = null;
		        HttpURLConnection httpUrl = null;
		        BufferedInputStream bis = null;
		        BufferedOutputStream bos = null;
		        File f = new File(localFilePath);
		        try
		        {
		            urlfile = new URL(remoteFilePath);
		            httpUrl = (HttpURLConnection)urlfile.openConnection();
		            httpUrl.connect();
		            bis = new BufferedInputStream(httpUrl.getInputStream());
		            bos = new BufferedOutputStream(new FileOutputStream(f));
		            int len = 2048;
		            byte[] b = new byte[len];
		            while ((len = bis.read(b)) != -1)
		            {
		                bos.write(b, 0, len);
		            }
		            bos.flush();
		            bis.close();
		            httpUrl.disconnect();
		        }
		        catch (Exception e)
		        {
		            e.printStackTrace();
		        }
		        finally
		        {
		            try
		            {
		                bis.close();
		                bos.close();
		            }
		            catch (IOException e)
		            {
		                e.printStackTrace();
		            }
		        }
		    }
		
		
}
